'use strict'

// Schema definition for facts
const factSchema = {
  type: 'object',
  properties: {
    text: { type: 'string' },
    category: { type: 'string' },
    source: { type: 'string' },
    verified: { type: 'boolean' },
    createdAt: { type: 'string', format: 'date-time' }
  },
  required: ['text', 'category']
}

// Get facts collection
const getFactsCollection = async (fastify) => {
  const db = fastify.mongo.db
  return db.collection('facts')
}

// Find facts
const findFacts = async (fastify, query = {}, limit = 10, skip = 0) => {
  const collection = await getFactsCollection(fastify)
  return collection.find(query)
    .sort({ createdAt: -1 })
    .skip(skip)
    .limit(limit)
    .toArray()
}

// Find random fact
const findRandomFact = async (fastify, category = null) => {
  const collection = await getFactsCollection(fastify)
  const query = category ? { category } : {}
  
  // Get count of matching documents
  const count = await collection.countDocuments(query)
  if (count === 0) return null
  
  // Get a random document
  const random = Math.floor(Math.random() * count)
  return collection.findOne(query, { skip: random })
}

// Insert fact
const insertFact = async (fastify, fact) => {
  const collection = await getFactsCollection(fastify)
  const newFact = {
    ...fact,
    verified: fact.verified || false,
    createdAt: new Date().toISOString()
  }
  const result = await collection.insertOne(newFact)
  return { ...newFact, _id: result.insertedId }
}

// Verify a fact
const verifyFact = async (fastify, id) => {
  const collection = await getFactsCollection(fastify)
  const result = await collection.findOneAndUpdate(
    { _id: new fastify.mongo.ObjectId(id) },
    { $set: { verified: true } },
    { returnDocument: 'after' }
  )
  return result.value
}

// Delete fact
const deleteFact = async (fastify, id) => {
  const collection = await getFactsCollection(fastify)
  return collection.deleteOne({ _id: new fastify.mongo.ObjectId(id) })
}

module.exports = {
  factSchema,
  findFacts,
  findRandomFact,
  insertFact,
  verifyFact,
  deleteFact
} 